//
//  OrderCarViewController.m
//  囧途
//
//  Created by Chen Victor on 16/3/4.
//  Copyright © 2016年 fly. All rights reserved.

#import "OrderCarViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <AVUser.h>
#import "LoginViewController.h"
#import <AVObject.h>
#import "MyOrderViewController.h"
#import <AVRelation.h>
@interface OrderCarViewController ()<CLLocationManagerDelegate>
{
CLLocationManager *_locationManager;
}

@property (weak, nonatomic) IBOutlet UIButton *agreeButton;

@property (weak, nonatomic) IBOutlet UIButton *foundCar;

@property (weak, nonatomic) IBOutlet UIButton *locationButton;

@property (weak, nonatomic) IBOutlet UIButton *bookButton;

@property (weak, nonatomic) IBOutlet UITextField *locationFiled;

@property (weak, nonatomic) IBOutlet UITextField *aimFiled;

@property (weak, nonatomic) IBOutlet UITextView *book;

@property(nonatomic, assign) BOOL ture;

@property(nonatomic, strong)AVUser * currentUser;

@end

@implementation OrderCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _currentUser = [AVUser currentUser];
    
    _ture = NO;
    
self.navigationItem.title = @"预约车";
    
    [self initializeLocationService];
    
}



- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    // 取得定位权限，有两个方法，取决于你的定位使用情况
    // 一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
    [_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
    [_locationManager startUpdatingLocation];
}

#pragma mark-delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // 获取当前所在的地理位置街道
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
  
            NSLog(@"%@",placemark.name);
            
            _locationFiled.text = placemark.name;

                   }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}
- (IBAction)locationButtonPressed:(UIButton *)sender {
   }

- (IBAction)bookButtonPressed:(UIButton *)sender {
    
}
- (IBAction)agreeButtonPressed:(UIButton *)sender {
    
    _ture = !_ture;
    
    
    
}
- (IBAction)findCarButtonPressed:(UIButton *)sender {
    //判断当前是否为登录状态
    if (_currentUser == nil) {
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"登录后才可以预约哦~" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * alertAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            LoginViewController * loginView = [[LoginViewController alloc]init];
            
            [self.navigationController pushViewController:loginView animated:YES];
            
            
        }];
        
        [alert addAction:alertAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
    else if([_locationFiled.text isEqualToString:@""] || [_aimFiled.text isEqualToString:@""]) {
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"出发地和目的地不能为空！" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * alertAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:alertAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        
    }

    
    
    else if  (_ture ==NO) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请同意条款" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * alertAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:alertAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
    
    
    else if (_currentUser !=nil && ![_locationFiled.text isEqualToString:@""] && ![_aimFiled.text isEqualToString:@""] && _ture ==YES) {
        
        AVObject * obj = [AVObject objectWithoutDataWithClassName:@"_User" objectId:_currentUser.objectId];
        
        AVRelation * relation = [obj relationForKey:@"Trip"];
        
        AVObject * trip = [AVObject objectWithClassName:@"Trip"];
        
        [trip setObject:_locationFiled.text forKey:@"start"];
        
        [trip setObject:_aimFiled.text forKey:@"end"];

        [trip save];
        
        [relation addObject:trip];
        
        [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
           
            if (succeeded) {
                
                
                
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"订单发送成功！" preferredStyle:UIAlertControllerStyleAlert];
                
                            UIAlertAction * alertAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                                [self.navigationController popToRootViewControllerAnimated:YES];
                
                            }];
                
                            [alert addAction:alertAction];
                            
                            [self presentViewController:alert animated:YES completion:nil];
                
            }
            
        }];
        
    }
    
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
 [self.view endEditing:YES];
}

@end
